package org.linlinjava.litemall.admin.service;

import cn.xuyanwu.spring.file.storage.FileInfo;
import cn.xuyanwu.spring.file.storage.FileStorageService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.linlinjava.litemall.admin.dto.AdminVersionHistoryDTO;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.LitemallStorage;
import org.linlinjava.litemall.db.domain.LitemallVersionHistory;
import org.linlinjava.litemall.db.service.LitemallStorageService;
import org.linlinjava.litemall.db.service.LitemallVersionHistoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class AdminVersionHistoryService {

    private final LitemallVersionHistoryService versionHistoryService;
    private final LitemallStorageService litemallStorageService;
    private final FileStorageService fileStorageService;

    public ResponseUtil.Response versionHistoey(Integer limit, Integer page) {
        IPage<LitemallVersionHistory> versionHistories = versionHistoryService.page(new Page<>(page,limit),Wrappers.lambdaQuery(LitemallVersionHistory.class).orderByDesc(LitemallVersionHistory::getAddTime));
        return ResponseUtil.okPage(versionHistories);
    }

    public ResponseUtil.Response versionHistoeyDdd(AdminVersionHistoryDTO adminVersionHistoryDTO) {
        LitemallVersionHistory versionHistory = LitemallVersionHistory.builder()
                .isNew(true)
                .addTime(LocalDateTime.now())
                .build();
        BeanUtils.copyProperties(adminVersionHistoryDTO, versionHistory);
        versionHistory.setContent(adminVersionHistoryDTO.getContent().split("\n"));
        versionHistory.setKeep(adminVersionHistoryDTO.getKeep().split("\n"));
        versionHistoryService.save(versionHistory);
        //清除其它更新包 isNew
        versionHistoryService.removeIsNewById(versionHistory.getId());
        return ResponseUtil.ok();
    }

    public ResponseUtil.Response versionHistoeyDelete(Integer id) {
        return versionHistoryService.removeById(id) ? ResponseUtil.ok(id) : ResponseUtil.fail(id);
    }

    public ResponseUtil.Response versionHistoeyDetails(Integer id) {
        return ResponseUtil.ok(versionHistoryService.getById(id));
    }

    public synchronized ResponseUtil.Response uploadFile(MultipartFile file) {
        //判断是什么包
        String fileName = file.getOriginalFilename().substring(0, 3).toLowerCase();
        int dotIndex = file.getOriginalFilename().lastIndexOf(".");
        String fileType = file.getOriginalFilename().substring(dotIndex + 1).toLowerCase();
        Integer isType = 0;
        if ("app".equals(fileName) && ("apk".equals(fileType)||"1".equals(fileType))) {
            isType = 1;
        } else if ("pos".equals(fileName) && ("apk".equals(fileType)||"1".equals(fileType))) {
            isType = 2;
        } else if ("docx".equals(fileType)) {
            //是word文档
            isType = 3;
        }
        else {
            return ResponseUtil.ok(201);
        }
        FileInfo fileInfo = fileStorageService.of(file)
                .setPath("version/"+ LocalDate.now()+"/")
                .setSaveFilename(file.getOriginalFilename())
                .upload();
        //上传的原图
        LitemallStorage storageOriginalInfo = new LitemallStorage();
        storageOriginalInfo.setName(fileInfo.getOriginalFilename());
        String s = String.valueOf(fileInfo.getSize());
        storageOriginalInfo.setSize(Integer.valueOf(s));
        storageOriginalInfo.setType(fileInfo.getContentType());
        storageOriginalInfo.setKey(fileInfo.getFilename());
        storageOriginalInfo.setUrl(fileInfo.getUrl());
        storageOriginalInfo.setAddTime(LocalDateTime.now());
        storageOriginalInfo.setUpdateTime(LocalDateTime.now());
        storageOriginalInfo.setDeleted(false);
        storageOriginalInfo.setFileType(isType);
        //批量存储
        boolean save = litemallStorageService.save(storageOriginalInfo);
        return save ? ResponseUtil.ok(storageOriginalInfo) : ResponseUtil.fail();
    }


    public void downloadFile(String fileUrl, String fileName, HttpServletResponse response)  {
        try (BufferedInputStream in = new BufferedInputStream(new URL(fileUrl).openStream());
             BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream())) {
            // 设置响应头
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
            out.flush();
        } catch (IOException e) {
           log.error("文件下载失败！{}",e.getMessage());
        }
    }
}
